﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using AspNetCs.Common;
using System.Web;
using System.Data;
using System.IO;

namespace AspNetCs.Bll
{
    public class GetStringData_lable
    {
        #region 匹配串
        private Regex rx = new Regex(@"(?<AllLabel>\<!--\$(?<label>.*?)\$--\>)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取系统标签
        private Regex cusrx = new Regex(@"(?<CustomName>\{@YX_\w+\})", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取自定义标签
        private string pageItem = @"(?<AllPagerStr>\<\$\>[\s\S]*?(?<Pager>\<pager(2)?\((?<PageSize>\b\d+\b)(\,(?<PagerStyle>\b\d+\b)\)?)?\>)[\s\S]*?\<\/\$\>)";//获取表名称
        private string rxItem = @"\[\*(?<TableName>.*)\*\]";//获取表名称
        // private string customItem = @"(?<CustomName>\{@\w+\})";//获取自定义标签名称 
        private string VItem = @"\{(?<Total>\b\d+\b)?(\((?<VValue>\b\d+\b)\))?[\s\S]*?(where\((?<Wheres>.*)\))?[\s\S]?(order\<(?<OrderName>.*)\>)?\}";//获取需要返回显示的记录数(每行几个)<查询条件>*排序字段*
        private Regex queryStringParamItem = new Regex(@"@(?<QSPItem>[_a-zA-Z]+)@", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取超链接传值参数
        private static string rxItemPat = @"(?<ItemName>\[(?<HName>\w+)(\((?<PValue>\b\d+\b)?\))?\])?";
        private Regex rxItemColumn = new Regex(rxItemPat, RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取显示的字段映射名称

        #endregion


        #region 匹配串

        private Regex Currrx = new Regex(@"(?<AllLabel>\[\$(?<ColumnName>.*?)\$\])", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取系统标签
        private Regex Currrxlen = new Regex(@"(\[\$(?<ColumnName>(\w+))\((?<strLen>(.+?))\)\$\])", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取系统标签
        private Regex RxTableColuns = new Regex(@"(\[\$(?<TableName>(\w+))\.(?<Cols>(\w+))\(\@(?<SearchColun>(.+?))\@\)\$\])", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled);//获取系统标签

        #endregion




        /// <summary>
        /// 替换标签处理[$列名所对应的中文字段$],必须设置FirstTable参数,且必须与DataTable中数据字段一致
        /// </summary>
        /// <param name="_input">内容</param>
        /// <param name="dt">DataTable</param>
        /// <param name="FirstTable">表名,必须与DataTable中数据字段一致</param>
        /// <returns></returns>
        public string GetResultStr(string _input, string FirstTable, DataTable dt)
        {


            string input = _input;

            #region 系统标签替换
            input = System_Lable.GetSysInfo(input);
            #endregion

            #region 替换标签格式为[$标签内容$]为DataTable里面的值

            MatchCollection Currmatches = Currrx.Matches(input);

            foreach (Match match in Currmatches)
            {
                string ColsName = match.Groups["ColumnName"].ToString();
                //string NewColsName = ColsName;

                string NewColsName = tblNameList.GetWhere("|" + ColsName + "|", FirstTable);//取字段名称 

                foreach (DataRow dr in dt.Rows)
                {
                    if (dt.Columns.Contains(NewColsName))
                    {
                        input = input.Replace(match.Value, dr[NewColsName].ToString());
                    }
                    break;
                }

            }

            #endregion

            new tblNameList(FirstTable);


            //input = Dynamic_Lable(input);

            return input;
        }


        /// <summary>
        /// 替换标签处理[$列名$],且必须与DataTable中数据字段一致
        /// </summary>
        /// <param name="_input"></param>
        /// <param name="Newdt"></param>
        /// <returns></returns>
        public string GetResultStr(string _input, DataTable Newdt)
        {
            try
            {
                #region 系统标签替换
                _input = System_Lable.GetSysInfo(_input);
                #endregion

                if (Newdt != null)
                {
                    if (Newdt.Rows.Count > 0)
                    {
                        #region 替换标签格式为[$列名$]为DataTable里面的值
                        MatchCollection Currmatches = Currrx.Matches(_input);

                        foreach (Match match in Currmatches)
                        {
                            string ColsName = match.Groups["ColumnName"].Value.ToString();
                            //string NewColsName = ColsName;

                            if (Newdt.Columns.Contains(ColsName))
                            {
                                _input = _input.Replace(match.Value, Newdt.Rows[0][ColsName].ToString());
                            }
                        }

                        #endregion

                        #region 替换[$列名(格式化样式)$]

                        MatchCollection Currlenmatches = Currrxlen.Matches(_input);

                        foreach (Match match in Currlenmatches)
                        {
                            string ColsName = match.Groups["ColumnName"].Value.ToString();
                            string ColsLen = match.Groups["strLen"].Value.ToString();
                            //string NewColsName = ColsName;
                            if (Newdt.Columns.Contains(ColsName))
                            {
                                _input = _input.Replace(match.Value, StringHelper.FormatContent(Newdt.Columns[ColsName].DataType, ColsLen.ToString(), Newdt.Rows[0][ColsName].ToString()));
                            }
                        }

                        #endregion



                        MatchCollection RxTableColunsSearch = RxTableColuns.Matches(_input);

                        foreach (Match match in RxTableColunsSearch)
                        {
                            string tbName = match.Groups["TableName"].Value.ToString();
                            string tbCols = match.Groups["Cols"].Value.ToString();
                            string CurrColumn = match.Groups["SearchColun"].Value.ToString();




                            //_input = _input.Replace(match.Value, tbName + tbCols + CurrColumn);
                            DataTable dt = TempleBll.CreateNew.GetTable(tbName, " " + GetTableKey(tbName) + "=" + Newdt.Rows[0][CurrColumn].ToString());
                            if (dt != null)
                            {
                                if (tbName == "UserPhoto_class" && CurrColumn == "classid" && dt.Rows.Count <= 0)
                                {
                                    _input = _input.Replace(match.Value, "点歌");
                                }
                                else
                                {
                                    if (dt.Rows.Count > 0)
                                    {
                                        if (dt.Columns.Contains(tbCols))
                                        {
                                            _input = _input.Replace(match.Value, dt.Rows[0][tbCols].ToString());
                                        }
                                    }
                                    else
                                    {
                                        _input = _input.Replace(match.Value, "");
                                    }
                                }
                            }
                            else
                            {
                                _input = _input.Replace(match.Value, "");
                            }





                        }






                    }
                }





            }
            catch
            {

            }
            return _input;
        }

        #region 动态标签的替换Dynamic_Lable(string _input)，针对单表

        public string Dynamic_Lable(string _input)
        {
            string input = _input;
            #region 系统数据标签处理
            int errnum = 0;
            MatchCollection matches = rx.Matches(input);

            foreach (Match match in matches)
            {
                string tblName = Regex.Match(match.Groups["label"].Value, rxItem).Groups["TableName"].ToString(); //直接取表名称 
                string TotalNum = Regex.Match(match.Groups["label"].Value, VItem).Groups["Total"].ToString();//获取总记录数     
                string VNum = Regex.Match(match.Groups["label"].Value, VItem).Groups["VValue"].ToString();//获取列数
                string WhereStr = Regex.Match(match.Groups["label"].Value, VItem).Groups["Wheres"].ToString();//获取查询条件   
                new tblNameList(tblName);
                string realWhere = tblNameList.GetWhere(WhereStr, tblName);//获取真实查询条件
                MatchCollection itemQueryStringParams = queryStringParamItem.Matches(realWhere);//匹配获取超链接值变量
                string qsStr = "";
                StringBuilder QSSB = new StringBuilder();

                foreach (Match itemQSP in itemQueryStringParams)
                {
                    string QSName = itemQSP.Groups["QSPItem"].Value;

                    if (!string.IsNullOrEmpty(QSName))
                    {
                        QSSB.Append("," + QSName);
                    }
                }
                qsStr = QSSB.ToString();
                if (!string.IsNullOrEmpty(qsStr))
                {
                    qsStr = qsStr.Substring(1);
                }
                realWhere = tblNameList.GetQueryStringParams(realWhere, qsStr);

                //input = ("tblName=" + tblName + "<br>");
                //input += ("TotalNum=" + TotalNum + "<br>");
                //input += ("VNum=" + VNum + "<br>");
                //input += ("WhereStr=" + WhereStr + "<br>");
                //input += ("qsStr=" + qsStr + "<br>");

                //input += ("realWhere=" + realWhere + "<br>");
                //string FilePath = HttpContext.Current.Server.MapPath("~/Config/Cemetery.config");
                //Xmlwork xml = new Xmlwork(FilePath);

                //DataSet ds = xml.GetData("//Root");
                //input += ("<br>开始---<br>");

                //if (ds != null)
                //{
                //    int i = 0;
                //    foreach (DataRow dr in ds.Tables[0].Rows)
                //    {
                //        i++;
                //        input += ("<br>dr=" + dr[i].ToString() + "行数=" + ds.Tables[0].Columns.Count);
                //    }
                //}
                //input += ("<br>结束---<br>");


            }





            #endregion
            return input;
        }

        #endregion


        /// <summary>
        /// 根据表名，返回Web.config中所对应的主键值,如果不存在，则返回ID
        /// </summary>
        /// <param name="tbName"></param>
        /// <returns></returns>
        public string GetTableKey(string tbName)
        {
            string Result = "";

            try
            {
                string ReadConfigKey = StringHelper.ReadConfig("TableKey");
                string[] ReadConfigKeyItems = StringHelper.SplitString(ReadConfigKey, "|");
                foreach (string str in ReadConfigKeyItems)
                {
                    string[] strItem = StringHelper.SplitString(str, ".");
                    if (strItem.Length > 1)
                    {
                        if (tbName == strItem[0].ToString())
                        {
                            Result = strItem[1].ToString();
                            break;
                        }
                    }

                }
            }
            catch
            {
                Result = " id ";
            }
            finally
            {
                if (Result == "")
                {
                    Result = " id ";
                }
            }
            return Result;
        }



        /// <summary>
        /// 替换标签处理,DataTable必须设置表名(TableName),且必须与数据库中表名一致
        /// </summary>
        /// <param name="_input">内容</param>
        /// <returns></returns>
        public string GetResultStr(StringBuilder stb, DataTable dt)
        {
            return GetResultStr(stb.ToString(), dt.TableName, dt);
        }





    }

    public class tblNameList
    {
        public tblNameList(string Tbname)
        {
            TableConfigCreate(Tbname.ToLower().Trim());
        }

        /// <summary>
        /// 生成传入表的XML数据
        /// </summary>
        /// <param name="TbName">生成的表名</param>
        public void TableConfigCreate(string TbName)
        {
            TbName = TbName.ToLower().Trim();//转换成小写
            try
            {
                DataTable dt = TempleBll.CreateNew.GetTableColumn(TbName);

                if (dt != null)
                {
                    string FilePath = HttpContext.Current.Server.MapPath("~/Config/" + StringHelper.ReadConfig("TableConfig"));
                    Xmlwork xml = new Xmlwork(FilePath);

                    DataSet dsTb = xml.GetDataSingle("//Root/" + TbName);
                    if (dsTb == null)
                    {
                        xml.InsertElement("Root", TbName, null);
                        xml.Save();
                    }
                    Xmlwork xml1 = new Xmlwork(FilePath);
                    foreach (DataRow dr in dt.Rows)
                    {

                        DataSet ds = xml.GetDataSingle("//Root/" + TbName + "/" + dr[1].ToString());
                        if (ds == null)
                        {
                            xml1.InsertElement("//Root/" + TbName, dr[1].ToString(), "无");
                        }
                    }
                    xml1.Save();


                }
            }

            catch
            {
            }
        }

        #region 获取条件
        /// <summary>
        /// GetWhere,查找表中的映射字段
        /// </summary>
        /// <param name="_where">传入的含映射字段的条件表达式</param>
        /// <param name="realTBLName">真实表名称</param>
        /// <returns>含有效字段名的查询表达式</returns>
        public static string GetWhere(string _where, string realTBLName)
        {
            realTBLName = realTBLName.ToLower().Trim();//转换成小写

            string retVal = _where;
            if (!string.IsNullOrEmpty(realTBLName))
            {
                string FilePath = HttpContext.Current.Server.MapPath("~/Config/" + StringHelper.ReadConfig("TableConfig"));
                Xmlwork xml = new Xmlwork(FilePath);
                DataTable dt = xml.GetDataTable("//Root/" + realTBLName);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataColumn dtc in dt.Columns)
                        {
                            retVal = retVal.Replace("|" + dt.Rows[0][dtc.ColumnName].ToString() + "|", dtc.ColumnName.ToLower().Trim());
                        }
                    }
                }
            }


            return retVal;
        }

        #endregion

        #region 获取传值
        public static string GetQueryStringParams(string _wval, string _qsval)
        {
            string getQSSting = HttpContext.Current.Request.ServerVariables["QUERY_STRING"];
            foreach (string _qsItem in _qsval.Split(','))
            {
                // _wval = _wval.Replace("@" + _qsItem + "@", "1111");

                foreach (string qsItem in getQSSting.Split('&'))
                {
                    if (_qsItem.Equals(qsItem.Split('=')[0]))
                    {
                        try
                        {
                            _wval = _wval.Replace("@" + _qsItem + "@", qsItem.Split('=')[1]);
                        }
                        catch
                        { }
                        break;
                    }
                }
            }
            return _wval;
        }
        #endregion






    }

}
